#include "WorkerThreadPool.h"
#include "BaseThread.h"

namespace dsth {

WorkerThreadPool::WorkerThreadPool() 
    : running_(false) {
}

WorkerThreadPool::~WorkerThreadPool() {

}

void WorkerThreadPool::Run(int num) {
    running_ = true;
    threads_.reserve(num);
    for (int i = 0; i < num; i++) {
        char id[32];
        snprintf(id, sizeof id, "%d", i);
        threads_.push_back(new BaseThread(std::make_pair(this, &WorkerThreadPool::WorkFun), id));
        threads_[i]->Run();
    }
}

void WorkerThreadPool::Stop() {
    running_ = false;
    int size = static_cast<int>(threads_.size());
    for (int i = 0; i < size; i++) {
        delete threads_[i];
    }
}

void WorkerThreadPool::Put(const WorkerTask& wt) {
    if (threads_.empty()) {
        wt();
    }
    else {
        queue_.put(wt);
    }
}

void WorkerThreadPool::WorkFun(const char* threadName) {
    while (running_) {
        WorkerTask task = queue_.take();
        task();
    }
}

} // namespace
